package com.edu.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BaseDao {
	public static final String DRIVER="com.mysql.cj.jdbc.Driver";
	public static final String URL="jdbc:mysql://localhost:3307/shop?characterEncoding=UTF-8";
	public static final String USER="root";
	public static final String PASS="123456";
	
	public static Connection getConn() {
		try {
			// 加载驱动
			Class.forName(DRIVER);
			// 创建连接
			Connection conn = DriverManager.getConnection(URL, USER, PASS);
			if (conn == null) {
				System.out.println("链接失败！");
			}
			return conn;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
//	public static void executeUpdate(String sql)  {
//		Connection conn=BaseDao.getConn();
//		//创建statement对象
//		Statement st =null ;
//		try {
//			st=conn.createStatement();
//			//执行sql语句
//			int num=st.executeUpdate(sql);
//			//返回执行结果
//			System.out.println("受影响行数为："+num);
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}finally {
//			BaseDao.closeAll(conn,st);
//		}
//		
//	}
	public static int executeUpdate(String sql,Object[] param) {
		Connection conn=null;
		//创建statement对象
		PreparedStatement ps =null ;
		int num=0;
		try { 
			conn=BaseDao.getConn();
			ps=conn.prepareStatement(sql);
			
			if (param != null) {
				for (int i = 0; i < param.length; i++) {
					ps.setObject(i+1,param[i]);
				}
				 num=ps.executeUpdate();
				 System.out.println(num);
				 System.out.println(ps);
			}else {
				 num=ps.executeUpdate(sql);
			}
			//执行sql语句
			
			return num;
			//返回执行结果
			//System.out.println("受影响行数为："+num);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			int errorCode = e.getErrorCode();
			return errorCode;
		}finally {
			BaseDao.closeAll(conn,ps);
		}
	}
	public static void closeAll(Connection conn,Statement st) {
		
		try {
			//st.close()关闭必须在conn前面
			if(st!=null)
			st.close();
			if(conn!=null)
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void closeAll(Connection conn,Statement st,ResultSet rs) {
		
		try {
			//st.close()关闭必须在conn前面
			if(st!=null)
				st.close();
			if(conn!=null)
				conn.close();
			if(rs!=null)
				rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
